<template>
    <div class="app-container">
        <!-- 付款单编辑 -->
        <h5 class="titleInfo">医院信息</h5>
        <!-- :rules="rules" -->
        <el-form ref="form" :inline="true" :model="form" label-width="130px" :rules="rules">
            <!-- 编辑查询模块 -->
            <div class="formDiv">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="医院名称">
                            <span class="spanToInput">{{hospitalEditList.hospitalName | filterNull}}</span>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="12">
                        <el-form-item label="回款比例">
                            <span class="spanToInput">{{hospitalEditList.paidRatio | filterNull}}</span>
                        </el-form-item>
                    </el-col>-->
                    <el-col :span="12">
                        <el-form-item label="付款单金额">
                            <span class="spanToInput">{{navNums[0] | filterMoney}}</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="应付款金额">
                            <span class="spanToInput">{{navNums[1] | filterMoney}}</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <!-- :required="isHaveTo" -->
                        <el-form-item label="付款卡号" prop="paidCard" >
                            <el-select
                                v-model="form.paidCard"
                                placeholder="请输入付款卡号"
                                filterable
                                :filter-method="dataFilter"
                                @change="paidCardFn(form.paidCard)"
                            >
                                <el-option
                                    :label="item.paidCard"
                                    :value="item.paidCard"
                                    v-for="(item,index) of cardSelect"
                                    :key="index"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <!-- :required="isHaveTo" -->
                        <el-form-item label="户名" prop="paidAccount" >
                            <el-select
                                v-model="form.paidAccount"
                                placeholder="请输入付款户名"
                                filterable
                                :filter-method="accountFilter"
                                @change="paidAccountFn(form.paidAccount)"
                            >
                                <el-option
                                    :label="item.paidAccount"
                                    :value="item.paidAccount"
                                    v-for="(item,index) in cardSelect"
                                    :key="index"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>
            <!-- 付款凭证 -->
            <el-form-item label="付款凭证">
                <newUpload
                    ref="uploadImg"
                    :fileNum="fileNum"
                    :fileList="fileList"
                    :width="-1"
                    :height="-1"
                />
            </el-form-item>
        </el-form>
        <div class="divBar" />
        <!-- 回款单信息 -->
        <h5 class="titleInfo">回款单信息</h5>
        <el-button class="addBtn" type="warning" @click="addReceivable()">新增回款单</el-button>
        <!-- 主页列表 -->
        <div class="listDiv" v-loading="tableLoading">
            <!-- table列表 -->
            <el-table
                :data="tableData"
                border
                style="width: 100%"
                show-summary
                :summary-method="getSummaries"
            >
                <el-table-column fixed type="index" width="50" label="序号"></el-table-column>
                <el-table-column prop="orderSn" label="流水单号"></el-table-column>
                <el-table-column prop="repaymentSn" label="回款单号"></el-table-column>
                <el-table-column prop="userName" label="客户姓名"></el-table-column>
                <el-table-column prop="userPhone" label="客户手机号"></el-table-column>
                <el-table-column prop="consultantName" label="咨询师姓名"></el-table-column>
                <el-table-column prop="currentAmount" label="本次回款金额">
                    <template slot-scope="scope">
                        <div v-if="scope.row.surplusReceivableAmount<0||scope.row.exceedDays>7">
                            <span>
                                {{scope.row.currentAmount = Number(scope.row.surplusReceivableAmount).toFixed(2)}}
                            </span>
                        </div>
                        <div v-else>
                            <!-- @blur="currentAmountBlur(scope.row.surplusReceivableAmount,scope.row.currentAmount,$event.target)" -->
                            <el-input v-model="scope.row.currentAmount">
                            </el-input>
                            <!-- <el-input
                                v-model="scope.row.currentAmount"
                                onkeyup="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"
                            ></el-input> -->
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="回款比率">
                    <template slot-scope="scope">
                        <div>{{Number(scope.row.paidRatio)}}%</div>
                    </template>
                </el-table-column>
                <el-table-column prop="paidAmount" label="应付款金额">
                    <template slot-scope="scope">
                        <!-- <div v-if="flags">{{scope.row.paidAmount = 0}}</div>
                        <div v-else>{{scope.row.paidAmount = (Number(scope.row.currentAmount * scope.row.paidRatio)/100).toFixed(2)}}</div> -->
                        <div>{{scope.row.paidAmount = (Number(scope.row.currentAmount * scope.row.paidRatio)/100).toFixed(2)}}</div>
                    </template>
                </el-table-column>
                <el-table-column prop="receivableAmount" label="应回款金额"></el-table-column>
                <el-table-column prop="receivedAmount" label="已回款金额"></el-table-column>
                <el-table-column prop="reviewAmount" label="审批中回款金额"></el-table-column>
                <el-table-column prop="surplusReceivableAmount" label="剩余回款金额"></el-table-column>
                <el-table-column prop="createdAt" label="创建时间"></el-table-column>
                <el-table-column prop="exceedDays" label="逾期天数"></el-table-column>
                <el-table-column fixed="right" label="操作" width="50">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            size="small"
                            :class="scope.row.exceedDays>7&&scope.row.isGrace=='0'?'flag':''"
                            @click="callFn(scope.$index,scope.row.id)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 提交按钮 -->
            <el-button type="primary" @click="submitFn('form')" class="submitBtn">立即提交</el-button>
            <el-dialog title="添加回款单" :visible.sync="dialogFormVisible" width="1600px" top="2vh">
                <receivableAdd ref="receivableAdds" @closeDialog="closeDialog" />
            </el-dialog>
        </div>
    </div>
</template>
<script>
import hospitalPay from "@/api/hospitalPay";
import phoneReg from "@/utils/validate";
import receivableAdd from "@/views/hospitalPay/receivableAdd";
import newUpload from "@/components/imgUpload/index";
export default {
    name: "hospitalPayEdit",
    components: { receivableAdd, newUpload },
    data() {
        // 验证活动名称的函数
        let validateCard = (rule, value, callback) => {
            // 当活动名称为空值且为必填时，抛出错误，反之通过校验
            if (this.form.paidCard === "" && this.isHaveTo) {
                callback(new Error("请输入卡号"));
            } else {
                callback();
            }
        };
        let validatepaidAccount = (rule, value, callback) => {
            // 当活动名称为空值且为必填时，抛出错误，反之通过校验
            if (this.form.paidAccount === "" && this.isHaveTo) {
                callback(new Error("请输入户名"));
            } else {
                callback();
            }
        };
        return {
            flags:false,
            imgList: [],
            fileList: [],
            fileNum: 5,
            dialogFormVisible: false,
            tableLoading: true,
            dates: [],
            // form表单
            form: {
                pageNum: 1,
                pageSize: 10,
                amount: "",
                paidAmount: "",
                paidAccount: "",
                paidCard: ""
            },
            // 银行卡号下拉表
            cardSelect: [],
            // table列表
            tableData: [],
            hospitalEditList: {},
            rules: {
                paidCard: [
                    { required: true, message: "请输入卡号", trigger: "blur" }
                ],
                paidAccount: [
                    { required: true, message: "请输入户名", trigger: "blur" }
                ]
            },
            navNums: [],
            paymentId:null,
        };
    },
    watch:{
        'tableData':{
            handler(newList , oldList) {
                newList.forEach(e=>{
                    if(Number(e.currentAmount)>Number(e.surplusReceivableAmount)){
                        e.currentAmount = null
                    }
                })
            },
            deep: true
        }
    },
    filters: {
        filterNull(e) {
            if (e) {
                return e;
            } else {
                return "暂无";
            }
        },
        filterMoney(e) {
            if (e) {
                return Number(e).toFixed(2);
            } else {
                return "暂无";
            }
        },
    },
    mounted() {
        let id = JSON.parse(this.$route.query.userId);
        this.paymentId= String(id)
        this.editList({ id: String(id) });
        this.cardList({ id: String(this.$store.state.user.hospitalId) });
    },
    inject: ["reload"],
    methods: {
        // 卡号
        paidCardFn(e){
            this.cardSelect.forEach(el => {
                if(el["paidCard"]==e){
                    this.form.paidAccount = el.paidAccount
                }
            });
        },
        //户名
        paidAccountFn(e){
            this.cardSelect.forEach(el => {
                if(el["paidAccount"]==e){
                    this.form.paidCard = el.paidCard
                }
            });
        },
        // 卡号自定义值
        dataFilter(val) {
            //    console.log(val)
            this.form.paidCard = val;
            // this.from.paidAccount = val;
            let newArr = [];
            if (val) {
                //val存在
                this.newArr = this.cardSelect.filter(item => {
                    if (
                        !!~item.paidCard.indexOf(val) ||
                        !!~item.paidCard
                            .toUpperCase()
                            .indexOf(val.toUpperCase())
                    ) {
                        return true;
                    }
                });
            } else {
                //val为空时，还原数组
                this.newArr = this.cardSelect;
            }
        },
        accountFilter(val) {
            //    console.log(val)
            this.form.paidAccount = val;
            // this.from.paidAccount = val;
            let newArr = [];
            if (val) {
                //val存在
                this.newArr = this.cardSelect.filter(item => {
                    if (
                        !!~item.paidAccount.indexOf(val) ||
                        !!~item.paidAccount
                            .toUpperCase()
                            .indexOf(val.toUpperCase())
                    ) {
                        return true;
                    }
                });
            } else {
                //val为空时，还原数组
                this.newArr = this.cardSelect;
            }
        },
        //获取列表
        editList(e) {
            hospitalPay
                .getDetails(e)
                .then(res => {
                    if (!res.data.code) {
                        let resData = res.data.data;
                        this.hospitalEditList = resData;
                        this.form.paidCard = resData.paidCard;
                        this.form.paidAccount = resData.paidAccount;
                        // this.tableData = resData.responseDTOS;
                        let imgList = [];
                        resData.images.forEach(i => {
                            imgList.push({
                                url: sessionStorage.getItem("imgUrlPrefix") + i
                            });
                        });
                        this.fileList = imgList;
                        // this.tableData = resData.responseDTOS;
                    } else {
                        this.$message({
                            showClose: true,
                            message: res.data.msg,
                            type: "warning"
                        });
                    }
                    this.tableLoading = false;
                })
                .catch(err => {
                    this.errorStatus(err);
                    this.tableLoading = false;
                });
        },
        // 添加回款单
        addReceivable() {
            this.dialogFormVisible = true;
            this.$nextTick(() => {
                this.$refs.receivableAdds.emptySelect();
            });
        },
        // 下拉列表
        cardList(e) {
            hospitalPay
                .cardList(e)
                .then(res => {
                    // console.log(res);
                    if (!res.data.code) {
                        let resData = res.data.data;
                        this.cardSelect = resData.cardDTOS;
                    } else {
                        this.$message({
                            showClose: true,
                            message: res.data.msg,
                            type: "warning"
                        });
                    }
                })
                .catch(err => {
                    this.errorStatus(res.msg);
                });
        },
        // table表数据合计
        getSummaries(param) {
            // console.log(param);
            //param 是固定的对象，里面包含 columns与 data参数的对象 {columns: Array[4], data: Array[5]},包含了表格的所有的列与数据信息
            const { columns, data } = param;
            // console.log("cc",columns)
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = "合计";
                    return;
                }
                let values;
                // console.log(column.property)
                if (
                    column.property == "currentAmount" ||
                    column.property == "paidAmount"
                ) {
                    values = data.map(item => Number(item[column.property]));
                } else {
                    values = data.map(item => String(item[column.property]));
                }
                // console.log(values);
                //验证每个value值是否是数字，如果是执行if
                if (
                    !values.every(value => isNaN(value)) &&
                    values.every(value => typeof value == "number")
                ) {
                    sums[index] = values.reduce((prev, curr) => {
                        return Number((prev + curr).toFixed(2));
                    }, 0);
                    sums[index] += "";
                } else {
                    sums[index] = "";
                }
            });
            this.navNums = sums.filter(e => {
                return e !== "" && e !== "合计";
            });
            return sums;
        },
        // 弹窗关闭
        closeDialog(e) {
            this.dialogFormVisible = false;
            this.tableData.push(...e);
            this.tableData.forEach(e => {
                for (let n in e) {
                    if(e[n]){
                        e[n] = String(e[n]);
                    }
                    if (n == "currentAmount" || n == "paidAmount") {
                        e[n] = 0;
                    }
                }
            });
            var result = [];
            var obj = {};
            for(var i =0; i<this.tableData.length; i++){
                if(!obj[this.tableData[i].repaymentSn]){
                    result.push(this.tableData[i]);
                    obj[this.tableData[i].repaymentSn] = true;
                }
            }
            this.tableData = result
            // this.dialogFormVisible = false;
            // this.tableData.push(...e);
            // this.tableData.forEach(e => {
            //     for (let n in e) {
            //         if (e[n]) {
            //             e[n] = String(e[n]);
            //         }
            //         if (n == "currentAmount" || n == "paidAmount") {
            //             e[n] = 0;
            //         }
            //     }
            // });
            // this.tableData = [...new Set(this.tableData)];
        },
        //弹窗组件
        eleMsg(txt, status) {
            this.$message({
                showClose: true,
                message: txt,
                type: status
            });
        },
        //成功状态弹窗
        succStatus(txt, status) {
            this.eleMsg(txt, "success");
        },
        //失败状态弹窗
        errorStatus(txt) {
            this.eleMsg(txt, "error");
        },
        // 警告状态弹窗
        warningStatus(txt) {
            this.eleMsg(txt, "warning");
        },
        // 路由跳转
        toRoutes(e, userId) {
            let route = { name: e, query: { userId: userId } };
            this.$router.push(route);
        },
        //改变页面条数
        handleSizeChange(val) {
            this.form.pageSize = val;
            this.getList(this.form);
        },
        //选择页数
        handleCurrentChange(val) {
            this.form.pageNum = val;
            this.getList(this.form);
        },
        // 立即提交
        submitFn(e) {
            let repayments = [];
            let amountArr = [];
            this.tableData.forEach(i => {
                repayments.push({
                    repaymentId: i.repaymentId,
                    amount: String(i.currentAmount)
                });
                amountArr.push(String(i.currentAmount))
            });
            if(amountArr.indexOf("0")==-1){
                let datas = {
                    paymentId:this.paymentId,
                    hospitalId: this.$store.state.user.hospitalId,
                    amount: this.navNums[0],
                    paidAmount: this.navNums[1],
                    paidAccount: this.form.paidAccount,
                    paidCard: this.form.paidCard,
                    images: this.$refs.uploadImg.submitUpload(),
                    repayments: repayments
                };
                if (Number(this.navNums[1])<0) {
                    this.errorStatus("应付款金额应大于等于0");
                } else {
                    this.$refs[e].validate(valid => {
                        if (valid) {
                            this.editSubmit(datas);
                        } else {
                            this.$message({
                                message: "有必填项没填，不能提交咯",
                                type: "warning"
                            });
                        }
                    });
                }
            }else{
                this.errorStatus("有条回款单本次回款金额为0，不能提交");
            } 
        },
        // 提交编辑
        editSubmit(e) {
            hospitalPay
                .editSubmitInfo(e)
                .then(res => {
                    if (!res.data.code) {
                        this.succStatus("提交成功");
                        this.$router.push("/hospitalPayIndex");
                        this.reload();
                    } else {
                        this.$message({
                            showClose: true,
                            message: res.data.msg,
                            type: "warning"
                        });
                    }
                })
                .catch(err => {
                    this.errorStatus(err);
                });
        },
        // 删除
        callFn(e) {
            this.tableData.splice(e, 1);
        },
        //confirm框
        eleConfirm(e) {
            this.$confirm(e.desc, e.title, {
                confirmButtonText: e.confirmBtnTxt,
                cancelButtonText: e.cancelBtnTxt,
                type: "warning"
            })
                .then(() => {
                    e.fn();
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: e.catchInfo
                    });
                });
        }
    }
};
</script>
<style scoped>
.addBtn {
    margin-left: 20px;
    margin-bottom: 20px;
}
/* 分页 */
.pagesCon {
    height: 40px;
    margin-top: 20px;
}
/* 主页列表样式 */
.listDiv {
    margin-bottom: 20px;
    padding: 0 20px;
}
.pagesCon > div {
    float: right;
}
.app-container {
    padding: 0.1px !important;
}
.form {
    margin-left: 20px;
}
.elFormImg {
    width: 268px;
}
.submitBtn {
    margin-top: 20px;
    margin-bottom: 20px;
}
.flag {
    display: none;
}
/* .active{
    display: block;
} */
</style>
